package loadbalance

import (
	"errors"
	"math/rand"
	"test2/pkg/ServiceInstance"
)

type LoadBalance interface {
	SelectService(service []*ServiceInstance.ServiceInstance) (*ServiceInstance.ServiceInstance, error)
}

type RandomLoadBalance struct {
}

func (loadBalance *RandomLoadBalance) SelectService(services []*ServiceInstance.ServiceInstance) (*ServiceInstance.ServiceInstance, error) {

	if services == nil || len(services) == 0 {
		return nil, errors.New("service instances are not exist")
	}

	return services[rand.Intn(len(services))], nil
}

type WeightLoadBalance struct {
}

func (loadBalance *WeightLoadBalance) SelectService(services []*ServiceInstance.ServiceInstance) (best *ServiceInstance.ServiceInstance, err error) {

	if services == nil || len(services) == 0 {
		return nil, errors.New("service instances are not exist")
	}

	total := 0
	for i := 0; i < len(services); i++ {
		w := services[i]
		if w == nil {
			continue
		}

		w.CurWeight += w.Weight

		total += w.Weight
		if best == nil || w.CurWeight > best.CurWeight {
			best = w
		}
	}

	if best == nil {
		return nil, nil
	}

	best.CurWeight -= total
	return best, nil
}
